﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using TSV.Models;
using TSV.Areas.Administration.Models;
using TSV.Library.Common;
using System.IO;

namespace TSV.Areas.Administration.Controllers
{
    public class CommonController : BaseController
    {
        private PartnerDao partnerDao = new PartnerDao();        
        private PromotionDao promotionDao = new PromotionDao();
        private CategoryDao cateDao = new CategoryDao();

        private Message CheckUploadFile(HttpPostedFileBase file, string allowExt)
        {
            Message msg = null;
            string ext = Path.GetExtension(file.FileName);
            int maxSize = 1024 * 1024 * Constants.UPLOAD_FILE_SIZE;
            float sizeFile = float.Parse(file.ContentLength.ToString("N"));
            if (file.ContentLength < 0)
            {
                msg = new Message(MessageConstants.E0011, MessageType.Error);
            }
            else if (sizeFile > maxSize)
            {
                msg = new Message(MessageConstants.E0012, MessageType.Error, Constants.UPLOAD_FILE_SIZE);
            }
            else if (!allowExt.Split(',').Contains(ext.ToLower()))
            {
                msg = new Message(MessageConstants.E0013, MessageType.Error, ext, allowExt, Constants.UPLOAD_FILE_SIZE);
            }
            return msg;

        }

        public ActionResult UploadImage()
        {            
            return View();
        }


        [HttpPost]
        public FileUploadJsonResult UploadSingleImage(FormCollection form)
        {            
            string saveTo = form["path"].Replace("/undefined", "");
            string recordID = form["recordID"];
            string img = form["value"];
            string controller = form["controller"];
            var principal = HttpContext.User as AuthenticationProjectPrincipal;
            FileUploadJsonResult result = new FileUploadJsonResult();
            Message msg = null;
            foreach (string file in Request.Files)
            {
                string uniqueId = DateTime.Now.ToString("MMddyyyyhhmmss");
                HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;

                if (hpf.ContentLength != 0)
                {
                    msg = CheckUploadFile(hpf, Constants.UPLOAD_ALLOW_IMG_EXT);                    
                    if (msg == null) //check successfull
                    {
                        string strPath = string.IsNullOrEmpty(recordID) == true ? Server.MapPath(Constants.UPLOAD_TEMP_PATH) : Server.MapPath(saveTo);
                        string imageName = uniqueId + "_" + Path.GetFileName(hpf.FileName);
                        imageName = ConvertUtil.FormatFileName(imageName);
                        hpf.SaveAs(strPath + imageName);
                        if (!string.IsNullOrEmpty(recordID))
                        {
                            switch (controller)
                            {
                                case Constants.PARTNER_DEFAULT_VALUE:
                                    Partner partner = partnerDao.GetPartnerByID(int.Parse(recordID));
                                    if (partner != null)
                                    {
                                        partner.Logo = imageName;
                                        partner.UpdatedBy = principal.UserData.UserName;
                                        msg = partnerDao.UpdateImage(partner);
                                    }
                                    break;
                                case Constants.PROMOTION_DEFAULT_VALUE:
                                    Promotion promotion = promotionDao.GetById(int.Parse(recordID));
                                    if (promotion != null)
                                    {
                                        promotion.Image = imageName;
                                        msg = promotionDao.UpdateImage(promotion);
                                    }
                                    break;
                                case Constants.CATEGORY_DEFAULT_VALUE:
                                    Category category = cateDao.GetByID(int.Parse(recordID));
                                    if (category != null)
                                    {
                                        category.Image = imageName;
                                        msg = cateDao.UpdateImage(category);
                                    }
                                    break;
                            }
                            if (msg.MsgType != MessageType.Error)
                            {
                                msg = new Message(MessageConstants.I0001, MessageType.Info, imageName, "upload");
                            }
                            else
                            {
                                msg = new Message(MessageConstants.E0014, MessageType.Error, "xóa hình.");
                            }
                            result.Data = new { msg };
                        }
                        else // case add new
                        {
                            msg = new Message(MessageConstants.I0001, MessageType.Info, imageName, "upload");
                            result.Data = new { msg };
                        }
                        if (!String.IsNullOrEmpty(img) && img != Constants.NO_IMAGE)
                        {
                            if (System.IO.File.Exists(strPath + img))
                                System.IO.File.Delete(strPath + img);
                        }
                    }
                    else  //error case
                    {
                        result.Data = new { msg };
                        
                    }
                }
                else
                {
                    msg = new Message(MessageConstants.E0011, MessageType.Error);
                    result.Data = new { msg };
                }
            }
            return result;
        }

        public ActionResult RemovePhoto(string controller, string image, string id)
        {
            var principal = HttpContext.User as AuthenticationProjectPrincipal;
            string strPath = string.Empty;
            Message msg = null;
            if (!string.IsNullOrEmpty(id))
            {
                switch (controller)
                {
                    case Constants.PARTNER_DEFAULT_VALUE:
                        Partner partner = partnerDao.GetPartnerByID(int.Parse(id));
                        if (partner != null)
                        {
                            partner.Logo = Constants.NO_IMAGE;                            
                            partner.UpdatedBy = principal.UserData.UserName;
                            msg = partnerDao.UpdateImage(partner);
                        }
                        break;
                    case Constants.PROMOTION_DEFAULT_VALUE:
                        Promotion promotion = promotionDao.GetById(int.Parse(id));
                        if (promotion != null)
                        {
                            promotion.Image = Constants.NO_IMAGE;
                            msg = promotionDao.UpdateImage(promotion);
                        }
                        break;
                    case Constants.CATEGORY_DEFAULT_VALUE:
                        Category category = cateDao.GetByID(int.Parse(id));
                        if (category != null)
                        {
                            category.Image = Constants.NO_IMAGE;
                            msg = cateDao.UpdateImage(category);
                        }                        
                        break;
                }
            }
            if (msg != null && msg.MsgType == MessageType.Error)
            {
                return Json(msg);
            }
            else
            {
                string strPathTemp = Server.MapPath(Constants.UPLOAD_TEMP_PATH);
                if (System.IO.File.Exists(strPathTemp + "\\" + image))
                    System.IO.File.Delete(strPathTemp + "\\" + image);
                switch (controller)
                {
                    case Constants.PARTNER_DEFAULT_VALUE:
                        strPath = Server.MapPath(Constants.PHOTO_PATH_ROOT_PARTNER) + image;
                        //strPath += "\\" + image;
                        if (System.IO.File.Exists(strPath))
                            System.IO.File.Delete(strPath);
                        if (!System.IO.File.Exists(strPath))
                        {
                            msg = new Message(MessageConstants.I0001, MessageType.Info, "Hình", "xóa");
                        }
                        else
                        {
                            msg = new Message(MessageConstants.E0014, MessageType.Error, "xóa hình.");
                        }
                        break;
                    case Constants.PROMOTION_DEFAULT_VALUE:
                        strPath = Server.MapPath(Constants.PHOTO_PATH_ROOT_PARTNER) + image;
                        //strPath += "\\" + image;
                        if (System.IO.File.Exists(strPath))
                            System.IO.File.Delete(strPath);
                        if (!System.IO.File.Exists(strPath))
                        {
                            msg = new Message(MessageConstants.I0001, MessageType.Info, "Hình", "xóa");
                        }
                        else
                        {
                            msg = new Message(MessageConstants.E0014, MessageType.Error, "xóa hình.");
                        }
                        break;
                    case Constants.CATEGORY_DEFAULT_VALUE:
                        strPath = Server.MapPath(Constants.PHOTO_PATH_ROOT_CATEGORY) + image;
                        //strPath += "\\" + image;
                        if (System.IO.File.Exists(strPath))
                            System.IO.File.Delete(strPath);
                        if (!System.IO.File.Exists(strPath))
                        {
                            msg = new Message(MessageConstants.I0001, MessageType.Info, "Hình", "xóa");
                        }
                        else
                        {
                            msg = new Message(MessageConstants.E0014, MessageType.Error, "xóa hình.");
                        }
                        break;
                }
            }
            return Json(msg);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadImage(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor, string langCode)
        {
            var principal = HttpContext.User as AuthenticationProjectPrincipal;
            Message msg = CheckUploadFile(upload, Constants.UPLOAD_ALLOW_IMG_EXT);
            string output = string.Empty;
            string url = string.Empty;
            if (msg != null)
            {
                url = Path.GetFullPath(upload.FileName);
                output = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + url + "\", \"" + msg.MsgText + "\");</script></body></html>";
            }
            else
            {
                string uniqueName = DateTime.Now.ToString(Constants.UNIQUE_TIME) + upload.FileName;
                string path = Server.MapPath(Constants.UPLOAD_FCK_IMG_PATH) + uniqueName;
                upload.SaveAs(path);
                url = Request.Url.GetLeftPart(UriPartial.Authority) + Constants.UPLOAD_FCK_IMG_PATH + uniqueName;
                output = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + url + "\");</script></body></html>";
            }
            return Content(output);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadFlash(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor, string langCode)
        {
            var principal = HttpContext.User as AuthenticationProjectPrincipal;
            Message msg = CheckUploadFile(upload, Constants.UPLOAD_ALLOW_FLASH_EXT);
            string output = string.Empty;
            string url = string.Empty;
            if (msg != null)
            {
                url = Path.GetFullPath(upload.FileName);
                output = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + url + "\", \"" + msg.MsgText + "\");</script></body></html>";
            }
            else
            {
                string uniqueName = DateTime.Now.ToString(Constants.UNIQUE_TIME) + upload.FileName;
                string path = Server.MapPath(Constants.UPLOAD_FCK_FLASH_PATH) + uniqueName;
                upload.SaveAs(path);
                url = Request.Url.GetLeftPart(UriPartial.Authority) + Constants.UPLOAD_FCK_FLASH_PATH + uniqueName;
                output = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + url + "\");</script></body></html>";
            }
            return Content(output);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteFCKImage(string DeleteFileName)
        {
            string sDeleteFileName = DeleteFileName;
            //sDeleteFileName = Request.QueryString["DeleteFileName"];
            sDeleteFileName = Server.MapPath(sDeleteFileName);
            if (System.IO.File.Exists(sDeleteFileName))
            {
                System.IO.File.Delete(sDeleteFileName);
            }
            Message msg = new Message(MessageConstants.I0001, MessageType.Info, "Hình", "xóa");
            return Json(msg);
            
        }

    }
}
